//
//  FQDColumnArticleFeedViewController.m
//  FakeQDaily
//
//  Created by mewxiv on 9/23/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDColumnArticleFeedViewController.h"
#import "FQDRegisterNavViewController.h"
#import "FQDSubscribeManager.h"
#import "FQDAccountManager.h"
#import "QDailyAPI.h"
#import "FQDRestModel.h"

#import "FQDColumnArticleFeedCellItemProvider.h"
#import "FQDColumnHeaderImageCell.h"
#import "FQDColumnHeaderAuthorCell.h"
#import "FQDColumnHeaderSubscribeCell.h"
#import "FQDNavigationView.h"
#import "MBProgressHUD+FQDExtension.h"

#import "Masonry.h"

@interface FQDColumnArticleFeedViewController () 

@property (nonatomic, strong) NSArray *authors;
@property (nonatomic, strong) NSArray *subscribers;
@property (nonatomic, strong) NSCache *sizingCells;
@property (nonatomic, weak) FQDColumnHeaderImageCell *headerImageCell;

@end

@implementation FQDColumnArticleFeedViewController

- (void)viewDidLoad
{
    self.disableRefreshHeader = YES;
    self.sizingCells = [[NSCache alloc] init];
    [self setupCellItemProvider];
    [self fetchAuthorsAndSubscribersInfo];
    
    [super viewDidLoad];
}

- (void)setupCellItemProvider
{
    FQDColumnArticleFeedCellItemProvider *provider = [[FQDColumnArticleFeedCellItemProvider alloc] init];
    provider.feedId = self.column.ID;
    self.provider = provider;
}

- (void)fetchAuthorsAndSubscribersInfo
{
    NSString *columnId = self.column.ID;
    WeakSelf;
    [[QDailyAPI sharedAPI] getColumnAuthorsAndSubscribersInfo:columnId completion:^(id responseObject, NSError *error) {
        NSNumber *status = [responseObject valueForKeyPath:@"meta.status"];
        if ([status integerValue] == 200) {
            id response = responseObject[@"response"];
            weakSelf.authors = [NSArray yy_modelArrayWithClass:[FQDAuthor class] json:response[@"authors"]];
            weakSelf.subscribers = [NSArray yy_modelArrayWithClass:[FQDAuthor class] json:response[@"subscribers"]];
            [weakSelf reloadData];
        }
    }];
}

- (void)popBack:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setColumn:(FQDColumn *)column
{
    _column = column;
    
    self.title = column.name;
}

#pragma mark - FQDBaseCellActionDelegate
- (void)collectionViewCell:(FQDColumnHeaderImageCell *)cell actionType:(NSInteger)actionType actionControl:(UIControl *)control userInfo:(NSDictionary *)userInfo
{
    if (actionType == FQDColumnHeaderImageCellActionSubscribe) {
        FQDSubscribeManager *subscribeManager = [FQDSubscribeManager sharedManager];
        [subscribeManager toggleSubscribeColumn:cell.column.ID
         completion:^(BOOL success, BOOL subscribed) {
            if (success) {
                cell.subscribed = subscribed;
            }
        }];
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    if (self.headerImageCell) {
        CGFloat maxHeight = [FQDColumnHeaderImageCell cellHeight];
        CGFloat offset = scrollView.contentOffset.y;
        if (maxHeight - offset >= 0) {
            CGRect frame = self.headerImageCell.frame;
            frame.origin.y = offset;
            frame.size.height = maxHeight - offset;
            self.headerImageCell.frame = frame;
        }
    }
}

#pragma mark - FQDFeedBaseViewController override
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForHeaderCellAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize size;
    if (indexPath.section == 0) {
        CGFloat cellHeight = [FQDColumnHeaderImageCell cellHeight];
        size = CGSizeMake(collectionView.frame.size.width, cellHeight);
    } else if (indexPath.section >= 1 && indexPath.section <= 2) {
        Class cellClass = [self headerCellClassAtIndexPath:indexPath inCollectionView:collectionView];
        NSString *cellClassName = NSStringFromClass(cellClass);
        UICollectionViewCell *headerCell = [self.sizingCells objectForKey:cellClassName];
        if (!headerCell) {
            headerCell = [[cellClass alloc] init];
            [self.sizingCells setObject:headerCell forKey:cellClassName];
        }
        [self configureHeaderCell:headerCell atIndexPath:indexPath inCollectionView:collectionView];
        CGSize preferredSize = [headerCell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];;
        size = CGSizeMake(collectionView.frame.size.width, preferredSize.height);
    }
    return size;
}

- (NSInteger)numberOfHeaderCellsInCollectionView:(UICollectionView *)collectionView
{
    NSInteger authorCellCount = ([self.authors count] > 0) ? 1 : 0;
    NSInteger subscriberCellCount = ([self.subscribers count] > 0) ? 1 : 0;
    return (1 + authorCellCount + subscriberCellCount);
}

- (NSArray *)cellClasses
{
    NSArray *superCellClasses = [super cellClasses];
    return [superCellClasses arrayByAddingObjectsFromArray:@[
                [FQDColumnHeaderImageCell class],
                [FQDColumnHeaderAuthorCell class],
                [FQDColumnHeaderSubscribeCell class]
            ]];
}

- (Class)headerCellClassAtIndexPath:(NSIndexPath *)indexPath inCollectionView:(UICollectionView *)collectionView
{
    NSMutableArray *headerArray = [NSMutableArray arrayWithObject:[FQDColumnHeaderImageCell class]];
    if ([self.authors count] > 0) {
        [headerArray addObject:[FQDColumnHeaderAuthorCell class]];
    }
    if ([self.subscribers count] > 0) {
        [headerArray addObject:[FQDColumnHeaderSubscribeCell class]];
    }
    return headerArray[indexPath.section];
}

- (void)configureHeaderCell:(UICollectionViewCell *)headerCell atIndexPath:(NSIndexPath *)indexPath inCollectionView:(UICollectionView *)collectionView
{
    if ([headerCell isKindOfClass:[FQDColumnHeaderImageCell class]]) {
        FQDColumnHeaderImageCell *imageCell =  (FQDColumnHeaderImageCell *)headerCell;
        imageCell.delegate = self;
        imageCell.column = self.column;
        self.headerImageCell = imageCell;
    } else if ([headerCell isKindOfClass:[FQDColumnHeaderAuthorCell class]]) {
        FQDColumnHeaderAuthorCell *authorCell = (FQDColumnHeaderAuthorCell *)headerCell;
        authorCell.authors = self.authors;
    } else if ([headerCell isKindOfClass:[FQDColumnHeaderSubscribeCell class]]) {
        FQDColumnHeaderSubscribeCell *subscribeCell = (FQDColumnHeaderSubscribeCell *)headerCell;
        subscribeCell.subscribers = self.subscribers;
    }
}

@end
